package im.yisme.view.ui.animation;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import im.yisme.R;
import im.yisme.view.ui.GameView;
import im.yisme.view.ui.animation.pojo.DoorPOJO;

public class Door extends Thread{

	private DoorPOJO door;
	
	private static final int ANIMATION_UPDATE_INTERVAL = 20;
	private static final int PAUSE_POLLING_INTERVAL = 500;
	
	
	private int status;
	private boolean isRunning;
	private int count;
	
	private static final int CLOSING = 0;
	private static final int LOADING = 1;
	private static final int OPENING = 2;
	
	private GameView view;
	
	public Door(DoorPOJO door, Resources res, GameView view){
		this.view = view;
		
		Bitmap door_left = BitmapFactory.decodeResource(res, R.drawable.door_left);
		Bitmap door_right = BitmapFactory.decodeResource(res, R.drawable.door_right);
		
		this.door = door;
		this.door.setDoor_left(door_left);
		this.door.setDoor_right(door_right);
		
		status = 0;
		isRunning = true;
		count = 0;
	}
	public void run(){
		
		while(isRunning){
			try {
				
				switch (status) {
				case CLOSING:
					
					if(door.getRightPoint().x - door.getLeftPoint().x > 400){
						PointF right = door.getRightPoint();
						PointF left = door.getLeftPoint();
						
						door.setRightPoint(new PointF(right.x-10, right.y));
						door.setLeftPoint(new PointF(left.x+10,left.y));
					}
					else {
						status = LOADING;
					}
					
					break;
				case LOADING:
					
					switch (count) {
					case 0:door.setLoadingText("加载音乐...");
					break;
					case 1:door.setLoadingText("加载乐谱...");
					break;
					case 2:door.setLoadingText("加载图片资源...");
					break;
					case 3:door.setLoadingText("计分，判定系统启动...");
					break;
					case 4:door.setLoadingText("活动下你的手指...");
					break;
					case 5:door.setLoadingText("精彩马上开始=。=");
					break;

					default:
						status = OPENING;
						door.setLoadingText("");
						view.finishLoading();
						break;
					}
					count++;
					Thread.sleep(PAUSE_POLLING_INTERVAL);
					
					break;
				case OPENING:
					
					if(door.getRightPoint().x - door.getLeftPoint().x < 1200){
						PointF right = door.getRightPoint();
						PointF left = door.getLeftPoint();
						
						door.setRightPoint(new PointF(right.x+10, right.y));
						door.setLeftPoint(new PointF(left.x-10,left.y));
					}
					else {
						isRunning = false;
					}
					
					break;
					
				default:
					break;
				}
				
				
				Thread.sleep(ANIMATION_UPDATE_INTERVAL);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		door.setRightPoint(null);
		
	}

	public void stopRunning(){
		isRunning = false;
	}
}
